package com.huawei.cloudapp.model.direct;

import static com.huawei.cloudapp.utils.CasConstantsUtil.X_AUTH_TOKEN;
import static java.net.HttpURLConnection.HTTP_OK;

import android.util.Log;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.huawei.cloudapp.model.OnRequestListener;
import com.huawei.cloudapp.model.bean.CustomException;
import com.huawei.cloudapp.model.bean.User;
import com.huawei.cloudapp.model.bean.direct.ServerList;
import com.huawei.cloudapp.utils.CasHttpUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ServerModel {
    private static final String TAG = "ServerModel";
    private int mTotalCount;

    public void getServerList(User user, String region, String projectId, int offset, int limit, OnRequestListener<ServerList.Server> onRequestListener) {
        if (Long.parseLong(user.getUserTokenExpireTimeByRegion(region)) < System.currentTimeMillis()) {
            onRequestListener.onFailure(new CustomException.TokenExpireException());
            return;
        }
        HashMap<String, String> requestHeader = new HashMap<String, String>();
        requestHeader.put(X_AUTH_TOKEN, user.getUserTokenByRegion(region));
        CasHttpUtils.get(getRequestUrl(region, projectId, offset, limit), requestHeader, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                onRequestListener.onFailure(e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                try {
                    onRequestListener.onSuccess(parseResponseToPhoneList(response), mTotalCount);
                } catch (Exception e) {
                    onRequestListener.onFailure(e);
                }
            }
        });
    }

    public List<ServerList.Server> parseResponseToPhoneList(Response response) throws Exception {
        if (response == null) {
            Log.e(TAG, "Failed to get response from server.");
            throw new CustomException.EmptyResponseFromServerException();
        }
        List<ServerList.Server> serverList = new ArrayList<>();
        if (response.code() == HTTP_OK) {
            String rspJsonStr = response.body().string();
            Gson gson = new Gson();
            ServerList rsp = gson.fromJson(rspJsonStr, ServerList.class);
            if (rsp == null) {
                Log.e(TAG, "handleGetPhoneListResponse: Failed to get rsp from json. " + response.code() + ", " + response.body().string());
                throw new CustomException.FailedToGetPhoneListException();
            }
            mTotalCount = rsp.getCount();
            serverList = rsp.getServers();
            if (serverList.size() == 0) {
                throw new CustomException.GetServerListEmptyException();
            }
        } else {
            Log.e(TAG, "handleGetPhoneListResponse: " + response.code() + ", " + response.body().string());
            throw new CustomException.FailedToGetPhoneListException();
        }
        return serverList;
    }

    public String getRequestUrl(String region, String projectId, int offset, int limit) {
        String url = "https://cph." + region + ".myhuaweicloud.com" + "/v1/" + projectId +"/cloud-phone/servers";
        if (offset >= 0) {
            url += "?offset=" + offset;
        }

        if (limit > 0) {
            url += "&limit=" + limit;
        }
        return url;
    }
}
